package com.joeyzh.table;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.joey.base.util.LogUtils;
import com.joey.protocol.NetClient;
import com.joey.protocol.ResponseError;
import com.joey.ui.CheckedModel;
import com.joey.ui.general.BaseActivity;
import com.joey.ui.widget.AlertMessage;
import com.joeyzh.base.IPresenter;
import com.joeyzh.net.UAResponseListener;
import com.joeyzh.odata.ODataUri;
import com.joeyzh.utils.AppConsts;
import com.joeyzh.utils.Caches;
import com.joeyzh.utils.StringParseHelper;
import com.joeyzh.widget.PopUpSpinner;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;



/**
 * Created by Joey on 2018/4/2.
 *
 * @author by Joey
 *         基础表单组件Presenter
 */

public class BaseTableLogPresenter extends IPresenter<BaseTableViewModel> {

    ILogPresenterCallback logPresenterCallback;

    private AlertDialog errorDialog;
    private String messageLog = "";

    public BaseTableLogPresenter(Context context, BaseTableViewModel tableItemViewModel) {
        super(context, tableItemViewModel);
    }

    public void setLogPresenterCallback(ILogPresenterCallback logPresenterCallback) {
        this.logPresenterCallback = logPresenterCallback;
    }

    @Override
    public void submit() {

    }

    @Override
    public boolean checkoutInfo() {
        for (int i = 0; i < mVm.getValues().size(); i++) {
            //不是必填项
            if (!TextUtils.isEmpty(mVm.getValues().get(i).isRequired())) {
                continue;
            }
            if ("false".equalsIgnoreCase(mVm.getValues().get(i).getParamValue())) {
                showError(String.format("请选择:【%s】", mVm.getValues().get(i).getText()));
                return false;
            }
            if (TextUtils.isEmpty(mVm.getValues().get(i).getParamValue())) {
                showError(String.format("请填写:【%s】", mVm.getValues().get(i).getText()));
                return false;
            }
        }
        return true;
    }

    /**
     * 根据表节点加载表数据
     *
     * @param
     */
    protected void loadFlowTable(final TableLogEntity entity) {
        if (logPresenterCallback != null) {
            logPresenterCallback.updateSuccess(entity);
        }
    }

    /**
     * 更新数据：包括本地暂存，或者服务器数据等
     *
     * @param entity
     */
    public void updateItemValue(TableLogEntity entity) {
        if (TextUtils.isEmpty(entity.getItemListJson())) {
            return;
        }
        if (logPresenterCallback != null) {
            logPresenterCallback.updateSuccess(entity);
        }
        // 遍历赋值
        for (TableLogItemEntity itemEntity : entity.getParamValues()) {
            String value = StringParseHelper.parseValue(entity.getItemListJson(), "ParamValue", itemEntity.getParamCode());
            if (value == null) {
                continue;
            }
            itemEntity.setParamValue(value);
            try {
                mVm.bindParamView(itemEntity);
            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.e(itemEntity.getParamCode());
            }
        }
    }

    /**
     * 更新配置信息
     */
    protected void loadBaseInfo(Collection<TableLogItemEntity> itemEntities) {
        for (TableLogItemEntity itemEntity : itemEntities) {
            if (null == itemEntity.getExtra() || itemEntity.getExtra().isEmpty()) {
                ((BaseActivity) mCtx).dismiss();
                continue;
            }
            loadBaseInfo(itemEntity);
        }
    }

    /**
     * 获取配置信息
     * @param itemEntity 每个下拉项
     */
    private void loadBaseInfo(final TableLogItemEntity itemEntity) {

        final TableLogItemEntity.ConfigBean configURL = new Gson().fromJson(itemEntity.getExtra(), new TypeToken<TableLogItemEntity.ConfigBean>() {
        }.getType());

        //无方法和实体名
        if (null == configURL.getAppName() || null == configURL.getEntityName() || configURL.getAppName().isEmpty() || configURL.getEntityName().isEmpty()) {
            return;
        }
        String url = String.format("sit-svc/Application/%s/odata/%s", configURL.getAppName(), configURL.getEntityName());

        //拼接接口
        ODataUri odataUri = new ODataUri.Builder(url).build();

        StringBuffer buffer = new StringBuffer();
        buffer.append(odataUri.getUrl());
        buffer.append("?");
        buffer.append(configURL.getOptionConfig());

        ((BaseActivity) mCtx).showDialogMessage("获取配置信息中...");
        new NetClient(Caches.getModuleTag()).httpGet(AppConsts.Url.getDomainRoot(),buffer.toString(), new UAResponseListener<JsonElement>() {
            @Override
            public void onResponse(JsonElement jsonElement, ResponseError responseError) throws JsonIOException {
                ((BaseActivity) mCtx).dismiss();
                if (!jsonElement.isJsonArray()) {
                    return;
                }
                List<CheckedModel> spList = new ArrayList<>();

                PopUpSpinner sp = mVm.getParamValueView(itemEntity.getParamCode());
                //获取筛选内容
                for (int i = 0; i < jsonElement.getAsJsonArray().size(); i++) {
                    JsonObject object = (JsonObject) jsonElement.getAsJsonArray().get(i);
                    String optionLabel = object.get(configURL.getOptionLabel()).getAsString();
                    String optionValue = object.get(configURL.getOptionValue()).getAsString();
                    spList.add(new CheckedModel(optionValue, optionLabel));
                }
                sp.setDataChanged(spList);
                sp.setSeletedById(itemEntity.getParamValue());
                sp.notifyDataSetChanged();
            }

            @Override
            public void onError(ResponseError responseError) throws Exception {
                ((BaseActivity) mCtx).dismiss();
                showError("获取配置信息失败:\n" + responseError.getMessage());
            }
        });
    }

    public void showError(final String msg) {
        messageLog += "\n" + msg;
        if (errorDialog == null) {
            errorDialog = AlertMessage.show(mCtx, messageLog, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    messageLog = "";
                }
            });
            errorDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    messageLog = "";
                }
            });
            errorDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    messageLog = "";
                }
            });
            return;
        }
        errorDialog.setMessage(messageLog);
        errorDialog.show();
    }

}
